package com.dx.mes.service.tool.service;


import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.*;
import com.dx.mes.common.transcoder.util.*;
import com.dx.mes.facade.tool.service.IFtptolopeService;
import com.dx.mes.facade.tool.service.IMtptoolpmService;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeI;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeIA;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeO;
import com.dx.mes.facade.tool.tx.Mtptoolpm.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;
import static com.dx.mes.common.transcoder.util.HCutil.String2Date;


@Service("mtptoolpmService")
public class MtptoolpmService implements IMtptoolpmService{
	private LogUtils logUtils;
	private static String TX_NAME = T_MTPTOOLPM;
	private static String[] Digit = { "yyyy-MM-dd 00:00:00","yyyy-MM-dd 23:59:59"};

	@Autowired
	private IBisToolDao bisToolDao;
	@Autowired
	private IRetToolPmDao retToolPmDao;
	@Autowired
	private IRetToolPmItemDao retToolPmItemDao;
	@Autowired
	private IRetToolPmListDao retToolPmListDao;
	@Autowired
	private IRetToolStDao retToolStDao;
	@Autowired
	private IBisPmItemDao bisPmItemDao;
	@Autowired
	private IFtptolopeService ftptolopeService;

	@Override
	public String subMainProc(String evt_no, String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(MtptoolpmService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(MtptoolpmService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");

		Session session = retToolPmDao.getCrSession();
		long rtnCode = _NORMAL;
		String outMsg = null;

		MtptoolpmI inTrx = new MtptoolpmI();
		MtptoolpmO outTrx = new MtptoolpmO();
		outTrx.setTrx_id(TX_NAME);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		outTrx.setType_id(TRX_OUT);


		try {
			inTrx = JacksonUtil.fromJson(strInMsg, MtptoolpmI.class);

			rtnCode = subMainProc2(inTrx, outTrx);
			if (rtnCode != _NORMAL) {
				TransactionAspectSupport.currentTransactionStatus()
						.setRollbackOnly();
				outTrx.setRtn_code(String.valueOf(rtnCode));
			} else {
				outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				session.flush();
			}
		} catch (Exception ex) {
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logUtils.error(Util.stackTraceToString(ex));
		} finally {
			outMsg = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + outMsg + "]");
		}
		return outMsg;
	}

	private long subMainProc2(MtptoolpmI inTrx, MtptoolpmO outTrx) {
		long lRc = _NORMAL;
		char actionType = inTrx.getAction_flg().toCharArray()[0];
		switch (actionType) {
			case 'Q': {//根据时间、设备查询保养计划
				lRc = queryFunc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'I': {//根据时间、设备查询保养计划
				lRc = queryPmSettingItem(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'F': {//查询设备保养计划，每个周期只查询最近一次未保养计划
				lRc = queryFirstPmSettingEveryPmCycleFunc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'A': {//新增保养计划
				lRc = saveToolPmSettingFunc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}

			case 'N': {//新增保养计划
				lRc = saveToolPmSettingFunc2(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}

			case 'U': {//更新保养计划
				lRc = updateToolPmSettingFunc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'D': {//删除保养计划
				lRc = deleteToolPmSettingFunc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'S': {//执行保养计划
				lRc = saveToolPmListFunc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'M': {//根据ToolId查询保养计划
				lRc = queryToolPmByToolId(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'E' :{//根据主键查询保养计划
				lRc = queryToolPmByEvtId(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			default: {
				outTrx.setRtn_mesg("Invalide type input: [" + actionType + "]");
				return E_MTPTOOLPM_INVALID_INPUT;
			}
		}
		return lRc;
	}

	/**
	 * 查询保养计划
	 * @param inTrx
	 * @param outTrx
	 * @return
	 */
	private long queryFunc(MtptoolpmI inTrx, MtptoolpmO outTrx) {
		long lRc = _NORMAL;
		String sql_condition ="WHERE 1=1";
		if(!Util.isSpaceCheck(inTrx.getFrom_date()) &&
				!Util.isSpaceCheck(inTrx.getTo_date())){
			sql_condition += " AND FROM_DATE BETWEEN '" + inTrx.getFrom_date()
					+ "' AND '" + inTrx.getTo_date() +  "'";
		}

		if(!Util.isSpaceCheck(inTrx.getTool_id_fk())){
			sql_condition += " AND TOOL_ID_FK='" + inTrx.getTool_id_fk() + "'";
		}

		if(!StringUtils.isEmpty(inTrx.getShift_id_fk())){
			sql_condition += " AND SHIFT_ID_FK ='" + inTrx.getShift_id_fk() +"'";
		}

		String sql_tool_pm = "SELECT A.EVT_SEQ_ID,A.TOOL_ID_FK,A.FROM_DATE,A.TO_DATE,A.PM_STAT,A.PM_SEQ_ID,A.PM_TYPE,B.DATA_DESC FROM "
				+ "(SELECT EVT_SEQ_ID,TOOL_ID_FK,FROM_DATE,TO_DATE,PM_STAT,PM_SEQ_ID,PM_TYPE FROM ret_tool_pm " + sql_condition + ") A "
				+ "LEFT JOIN "
				+ "(SELECT EXT_1,DATA_DESC FROM bis_data WHERE DATA_CATE='PMTP') B "
				+ "ON A.PM_TYPE=B.EXT_1 "
				+ "ORDER BY FROM_DATE ASC";

		List<Object[]> objList  =  retToolPmDao.findBySQL(sql_tool_pm);
		List<MtptoolpmOC> oaryCList = new ArrayList<MtptoolpmOC>();
		if(objList.size()>0){
			for(int i=0; i<objList.size(); i++){
				Object[] obj = objList.get(i);
				MtptoolpmOC oaryC = new MtptoolpmOC();
				oaryC.setTitle(obj[1].toString() + "，" + (obj[7] == null ? "未知保养类型" : obj[7].toString()));
				oaryC.setTool_id(obj[1].toString());
				oaryC.setEvt_seq_id(obj[0].toString());
				oaryC.setStart(obj[2].toString().substring(0, 10));
				oaryC.setPm_type(obj[6].toString());

				String pm_stat_color = "gray";//其他PM状态,灰色
				String text_color = "white";//白色
				if(PROC_WAIT.equals(obj[4].toString()) && Util.isDealy(obj[3].toString())){//到期未保养,红色
					pm_stat_color = "red";
				}else if(PROC_WAIT.equals(obj[4].toString())){//待保养，黄色
					pm_stat_color = "yellow";
					text_color = "black";
				}else if(PROC_IN_PROCESS.equals(obj[4].toString())){//保养中，蓝色
					pm_stat_color = "blue";
				}else if(PROC_COMPLETE.equals(obj[4].toString())){//保养完成，绿色
					pm_stat_color = "green";
				}
				oaryC.setColor(pm_stat_color);
				oaryC.setTextColor(text_color);
				oaryCList.add(oaryC);
			}
		}
		outTrx.setOaryC(oaryCList);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		return lRc;
	}

	/**
	 * 查询保养计划中设定的保养项目
	 * @param inTrx
	 * @param outTrx
	 * @return
	 */
	public long  queryPmSettingItem(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		List<MtptoolpmOB> oaryBList = new ArrayList<MtptoolpmOB>();
		String hql_tool_pm="From Ret_tool_pm where 1=1 and tool_id_fk='" + inTrx.getTool_id_fk()
				+ "' and from_date='" + inTrx.getFrom_date()
				+ "' and pm_type='" + inTrx.getPm_type() + "'";
		List<Ret_tool_pm> tool_pm_list = retToolPmDao.find(hql_tool_pm);
		if(!tool_pm_list.isEmpty()){
			Ret_tool_pm tool_pm = tool_pm_list.get(0);
			//根据pm_item_id获取保养项目
			String hql_tool_pm_item = "FROM Ret_tool_pm_item where pm_item_id_fk='" + tool_pm.getPm_item_id() +"'";
			List<Ret_tool_pm_item> tool_pm_item_list = retToolPmItemDao.find(hql_tool_pm_item);
			for(Ret_tool_pm_item tool_pm_item:tool_pm_item_list){
				MtptoolpmOB oaryB = new MtptoolpmOB();
				oaryB.setPm_type_fk(inTrx.getPm_type());
				oaryB.setData_dsc(tool_pm_item.getData_dsc());
				if(tool_pm_item.getL_spec() != null){
					oaryB.setL_spec(tool_pm_item.getL_spec().toString());
				}
				if(tool_pm_item.getU_spec() != null){
					oaryB.setU_spec(tool_pm_item.getU_spec().toString());
				}
				oaryB.setData_typ(tool_pm_item.getData_typ());
				oaryB.setData_cnt(tool_pm_item.getData_cnt());
				oaryB.setPm_note(tool_pm_item.getPm_note());
				oaryBList.add(oaryB);
			}
		}else{
			outTrx.setRtn_mesg("未找到设备代码[" + inTrx.getTool_id_fk()
					+ "][" + inTrx.getFrom_date()
					+ "][" + inTrx.getPm_type() + "的保养项目！");
			return E_RET_TOOL_PM_ITEM + E_READ_NOT_FOUND;
		}
		outTrx.setOaryB(oaryBList);
		return lRc;
	}

	public long queryFirstPmSettingEveryPmCycleFunc(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		List<MtptoolpmOA> oaryAList = new ArrayList<MtptoolpmOA>();
		String sql_tool_pm="SELECT A.PM_SEQ_ID,A.PM_TYPE,A.TOOL_ID_FK,A.PM_DATE,A.PM_END_DATE,B.TOOL_RUN_MODE,C.DATA_DESC,A.LINE_ID_FK,A.MAINTENANCE_MASTER,A.SHIFT_ID_FK,A.PLAN_DURATION,A.TECH_CONFIRM_FLG,A.PROD_CONFIRM_FLG FROM "
				+ "(SELECT PM_SEQ_ID,PM_TYPE,TOOL_ID_FK,MIN(FROM_DATE) AS PM_DATE,MIN(TO_DATE) AS PM_END_DATE,LINE_ID_FK,MAINTENANCE_MASTER,SHIFT_ID_FK,PLAN_DURATION,TECH_CONFIRM_FLG,PROD_CONFIRM_FLG FROM ret_tool_pm WHERE PM_STAT<>'COMP' "
				+ "GROUP BY PM_SEQ_ID,PM_TYPE,TOOL_ID_FK ORDER BY PM_DATE,TOOL_ID_FK) A "
				+ "LEFT JOIN "
				+ "(SELECT TOOL_ID_FK,TOOL_RUN_MODE FROM ret_tool_st) B "
				+ "ON A.TOOL_ID_FK=B.TOOL_ID_FK "
				+ "LEFT JOIN "
				+ "(SELECT EXT_1,DATA_DESC FROM bis_data WHERE DATA_CATE='PMTP') C "
				+ "ON A.PM_TYPE=C.EXT_1 "
				+ "WHERE 1=1";

		if(!Util.isSpaceCheck(inTrx.getTool_id_fk())){
			sql_tool_pm += " AND A.tool_id_fk ='" + inTrx.getTool_id_fk() + "'";
		}
		if(!Util.isSpaceCheck(inTrx.getBayIdSel())){
			sql_tool_pm += " AND A.line_id_fk ='" + inTrx.getBayIdSel() + "'";
		}
		if(!Util.isSpaceCheck(inTrx.getTool_model())){
			sql_tool_pm += " AND B.tool_run_mode ='" + inTrx.getTool_model() + "'";
		}

		if(!Util.isSpaceCheck(inTrx.getPm_type())){
			sql_tool_pm += " AND A.pm_type ='" + inTrx.getPm_type() + "'";
		}
		if(!Util.isSpaceCheck(inTrx.getPm_start_time())&&!Util.isSpaceCheck(inTrx.getPm_end_time())){
			sql_tool_pm += " AND A.PM_DATE between'" + inTrx.getPm_start_time() + "'AND '"+inTrx.getPm_end_time()+"'";
		}
		List<Object[]> objList = retToolPmDao.findBySQL(sql_tool_pm);
		if(objList.size()>0){
			for(int i=0; i<objList.size(); i++){
				Object[] obj = objList.get(i);
				MtptoolpmOA oaryA = new MtptoolpmOA();
				oaryA.setTool_id_fk(obj[2].toString());
				oaryA.setFrom_date(obj[3].toString().split(" ")[0]);
//				oaryA.setEnd_date(obj[4].toString());
				oaryA.setPm_type_fk(obj[1].toString());
				oaryA.setPm_seq_id(obj[0].toString());
				oaryA.setTool_model(obj[5] == null ? "" : obj[5].toString());
				oaryA.setPm_type_dsc(obj[6] == null ? "未知保养类型" : obj[6].toString());
				oaryA.setLine_id_fk(obj[7].toString());
				oaryA.setMaintenance_master(obj[8].toString());
				oaryA.setPlan_duration(obj[10].toString());
				oaryA.setShift_id_fk(obj[9].toString());
				oaryA.setTech_confirm_flg(obj[11].toString());
				oaryA.setProd_confirm_flg(obj[12].toString());
//				oaryA.setPm_person_cnt(obj[8].toString());
				oaryAList.add(oaryA);
			}
		}

		outTrx.setOaryA(oaryAList);
		return lRc;
	}

	/**
	 * 新增保养计划
	 * @param inTrx
	 * @param outTrx
	 * @return
	 */
	public long saveToolPmSettingFunc(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		//检查保养项目
		if(inTrx.getIaryA().isEmpty()){
			outTrx.setRtn_mesg("未设定保养项目，请确认！");
			return E_MTPTOOLPM_INVALID_INPUT;
		}

		String pm_seq_id = GUIDGenerator.javaGUID();
		String pm_item_id = GUIDGenerator.javaGUID();
		//保存当前日期后一年的设定Ret_tool_pm
		List<Ret_tool_pm> tool_pm_list = new ArrayList<Ret_tool_pm>();
		String[] pm_typ_st = inTrx.getPm_type().split("_");//"_"分割;
		String pm_typ = pm_typ_st[0].substring(pm_typ_st[0].length()-1, pm_typ_st[0].length());
		if("Y".equals(pm_typ)){
			Integer baseInt = pm_typ_st[0].length() == 1 ?
					1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
			Ret_tool_pm tool_pm = new Ret_tool_pm();
//			Date from_date = Util.getYearDateAfter(inTrx.getFrom_date()+" 23:59:59",0,baseInt,Digit[0]);
//			Date to_date = Util.getYearDateAfter(inTrx.getFrom_date()+" 23:59:59",0,baseInt,Digit[1]);
			String shiftIdFk = inTrx.getShift_id_fk();
			String from_date ="";
			String to_date ="";
			if("D".equals(shiftIdFk)){
				from_date = inTrx.getPm_start_time() + " 08:00:00";
				to_date = inTrx.getPm_start_time() + " 20:00:00";
			}else if("N".equals(shiftIdFk)){
				from_date = inTrx.getPm_start_time() + " 20:00:00";
				//第二天早上8:00:00
				String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
				to_date = tommorrow + " 08:00:00";
			}

			if(isSameSetting(from_date, inTrx.getTool_id_fk(), inTrx.getPm_type(), "")){
				outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
						+ "]，[" +from_date+ "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
				return E_MTPTOOLPM_PM_TYP_EXIST;
			}
			tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
			tool_pm.setPm_seq_id(pm_seq_id);
			tool_pm.setPm_item_id(pm_item_id);
			tool_pm.setPm_type(inTrx.getPm_type());
			tool_pm.setTool_id_fk(inTrx.getTool_id_fk());
			tool_pm.setPm_stat(PROC_WAIT);
			tool_pm.setPm_person_cnt(inTrx.getPm_person_cnt());
			tool_pm.setFrom_date(Timestamp.valueOf(from_date));
			tool_pm.setTo_date(Timestamp.valueOf(to_date));
			tool_pm.setLine_id_fk(inTrx.getLine_id_fk());
			tool_pm.setMaintenance_master(inTrx.getMaintenance_master());
			tool_pm.setShift_id_fk(inTrx.getShift_id_fk());
			tool_pm.setPlan_duration(inTrx.getPlan_duration());
			tool_pm.setTech_confirm_flg(inTrx.getTech_confirm_flg());
			tool_pm.setProd_confirm_flg(inTrx.getProd_confirm_flg());
			if("C".equals(inTrx.getChange_typ())){//只保存本次保养
				tool_pm.setAlm_id("Y");
			}else {
				tool_pm.setAlm_id("N");
			}
			tool_pm.setAc_pm_delay_flg("N");
			tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
			tool_pm.setEvt_usr(inTrx.getEvt_usr());
			tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
			tool_pm_list.add(tool_pm);
		}else if("Q".equals(pm_typ)){//季度保养
			Integer baseInt = pm_typ_st[0].length() == 1 ?
					1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
			Integer maxCount = 4 % baseInt == 0 ? 4 / baseInt : 4 / baseInt + 1;
			for(int i=0; i<maxCount; i++){//保存4个季度
				String shiftIdFk = inTrx.getShift_id_fk();
				String from_dateString  ="";
				String to_dateString ="";
				if("D".equals(shiftIdFk)){
					from_dateString = inTrx.getPm_start_time() + " 08:00:00";
					to_dateString = inTrx.getPm_start_time() + " 20:00:00";
				}else if("N".equals(shiftIdFk)){
					from_dateString = inTrx.getPm_start_time() + " 20:00:00";
					//第二天早上8:00:00
					String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
					to_dateString = tommorrow + " 08:00:00";
				}
				Date from_date = Util.getMonthDateAfter(from_dateString,i,3*baseInt,"yyyy-MM-dd HH:mm:ss");
				Date to_date = Util.getMonthDateAfter(to_dateString,i,3*baseInt,"yyyy-MM-dd HH:mm:ss");
				if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), "")){
					outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
							+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
					return E_MTPTOOLPM_PM_TYP_EXIST;
				}
				Ret_tool_pm tool_pm = new Ret_tool_pm();
				tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
				tool_pm.setPm_seq_id(pm_seq_id);
				tool_pm.setPm_item_id(pm_item_id);
				tool_pm.setPm_type(inTrx.getPm_type());
				tool_pm.setTool_id_fk(inTrx.getTool_id_fk());
				tool_pm.setPm_stat(PROC_WAIT);
				tool_pm.setPm_person_cnt(inTrx.getPm_person_cnt());
				Timestamp fromDate = new Timestamp(from_date.getTime());
				Timestamp toDate = new Timestamp(to_date.getTime());
				tool_pm.setFrom_date(fromDate);
				tool_pm.setTo_date(toDate);
				if("C".equals(inTrx.getChange_typ())){//只保存本次保养
					tool_pm.setAlm_id("Y");
				}else {
					tool_pm.setAlm_id("N");
				}
				tool_pm.setAc_pm_delay_flg("N");
				tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
				tool_pm.setEvt_usr(inTrx.getEvt_usr());
				tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
				tool_pm.setLine_id_fk(inTrx.getLine_id_fk());
				tool_pm.setMaintenance_master(inTrx.getMaintenance_master());
				tool_pm.setShift_id_fk(inTrx.getShift_id_fk());
				tool_pm.setPlan_duration(inTrx.getPlan_duration());
				tool_pm.setTech_confirm_flg(inTrx.getTech_confirm_flg());
				tool_pm.setProd_confirm_flg(inTrx.getProd_confirm_flg());
				tool_pm_list.add(tool_pm);
				if("C".equals(inTrx.getChange_typ())){//只保存本次保养
					break;
				}
			}
		}else if("M".equals(pm_typ)){//月保养
			Integer baseInt = pm_typ_st[0].length() == 1 ?
					1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
			Integer maxCount = 12 % baseInt == 0 ? 12 / baseInt : 12 / baseInt + 1;
			for(int i=0; i<maxCount; i++){
				String shiftIdFk = inTrx.getShift_id_fk();
				String from_dateString  ="";
				String to_dateString ="";
				if("D".equals(shiftIdFk)){
					from_dateString = inTrx.getPm_start_time() + " 08:00:00";
					to_dateString = inTrx.getPm_start_time() + " 20:00:00";
				}else if("N".equals(shiftIdFk)){
					from_dateString = inTrx.getPm_start_time() + " 20:00:00";
					//第二天早上8:00:00
					String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
					to_dateString = tommorrow + " 08:00:00";
				}

				Date from_date = Util.getMonthDateAfter(from_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
				Date to_date = Util.getMonthDateAfter(to_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
				if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), "")){
					outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
							+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
					return E_MTPTOOLPM_PM_TYP_EXIST;
				}
				Ret_tool_pm tool_pm = new Ret_tool_pm();
				tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
				tool_pm.setPm_seq_id(pm_seq_id);
				tool_pm.setPm_item_id(pm_item_id);
				tool_pm.setPm_type(inTrx.getPm_type());
				tool_pm.setTool_id_fk(inTrx.getTool_id_fk());
				tool_pm.setPm_stat(PROC_WAIT);
				tool_pm.setPm_person_cnt(inTrx.getPm_person_cnt());
				Timestamp fromDate = new Timestamp(from_date.getTime());
				Timestamp toDate = new Timestamp(to_date.getTime());
				tool_pm.setFrom_date(fromDate);
				tool_pm.setTo_date(toDate);
				if("C".equals(inTrx.getChange_typ())){//只保存本次保养
					tool_pm.setAlm_id("Y");
				}else {
					tool_pm.setAlm_id("N");
				}
				tool_pm.setAc_pm_delay_flg("N");
				tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
				tool_pm.setEvt_usr(inTrx.getEvt_usr());
				tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
				tool_pm.setLine_id_fk(inTrx.getLine_id_fk());
				tool_pm.setMaintenance_master(inTrx.getMaintenance_master());
				tool_pm.setShift_id_fk(inTrx.getShift_id_fk());
				tool_pm.setPlan_duration(inTrx.getPlan_duration());
				tool_pm.setTech_confirm_flg(inTrx.getTech_confirm_flg());
				tool_pm.setProd_confirm_flg(inTrx.getProd_confirm_flg());
				tool_pm_list.add(tool_pm);
				if("C".equals(inTrx.getChange_typ())){//只保存本次保养
					break;
				}
			}
		}else if("W".equals(pm_typ)){//周保养
			Integer baseInt = pm_typ_st[0].length() == 1 ?
					1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
			Integer maxCount = 52 % baseInt == 0 ? 52 / baseInt : 52 / baseInt + 1;
			for(int i=0; i<maxCount; i++){
				String shiftIdFk = inTrx.getShift_id_fk();
				String from_dateString  ="";
				String to_dateString ="";
				if("D".equals(shiftIdFk)){
					from_dateString = inTrx.getPm_start_time() + " 08:00:00";
					to_dateString = inTrx.getPm_start_time() + " 20:00:00";
				}else if("N".equals(shiftIdFk)){
					from_dateString = inTrx.getPm_start_time() + " 20:00:00";
					//第二天早上8:00:00
					String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
					to_dateString = tommorrow + " 08:00:00";
				}
				Date from_date = Util.getWeekOfYearDateAfter(from_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
				Date to_date = Util.getWeekOfYearDateAfter(to_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
				if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), "")){
					outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
							+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
					return E_MTPTOOLPM_PM_TYP_EXIST;
				}
				Ret_tool_pm tool_pm = new Ret_tool_pm();
				tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
				tool_pm.setPm_seq_id(pm_seq_id);
				tool_pm.setPm_item_id(pm_item_id);
				tool_pm.setPm_type(inTrx.getPm_type());
				tool_pm.setTool_id_fk(inTrx.getTool_id_fk());
				tool_pm.setPm_stat(PROC_WAIT);
				tool_pm.setPm_person_cnt(inTrx.getPm_person_cnt());
				Timestamp fromDate = new Timestamp(from_date.getTime());
				Timestamp toDate = new Timestamp(to_date.getTime());
				tool_pm.setFrom_date(fromDate);
				tool_pm.setTo_date(toDate);
				if("C".equals(inTrx.getChange_typ())){//只保存本次保养
					tool_pm.setAlm_id("Y");
				}else {
					tool_pm.setAlm_id("N");
				}
				tool_pm.setAc_pm_delay_flg("N");
				tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
				tool_pm.setEvt_usr(inTrx.getEvt_usr());
				tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
				tool_pm.setLine_id_fk(inTrx.getLine_id_fk());
				tool_pm.setMaintenance_master(inTrx.getMaintenance_master());
				tool_pm.setShift_id_fk(inTrx.getShift_id_fk());
				tool_pm.setPlan_duration(inTrx.getPlan_duration());
				tool_pm.setTech_confirm_flg(inTrx.getTech_confirm_flg());
				tool_pm.setProd_confirm_flg(inTrx.getProd_confirm_flg());
				tool_pm_list.add(tool_pm);
				if("C".equals(inTrx.getChange_typ())){//只保存本次保养
					break;
				}
			}
		}else{
			outTrx.setRtn_mesg("除年保养(Y)、季度保养(Q)、月保养(M)、周保养(W)及这四种类型的整数倍保养如(2W、2Q、2M等等)，其他保养类型暂不支持，请联系系统开发人员！");
			return E_MTPTOOLPM_INVALID_PM_TYPE;
		}

		try {
			retToolPmDao.saveOrUpdateAll(tool_pm_list);
		} catch (Exception e) {
			outTrx.setRtn_mesg(e.getCause().getMessage());
			return E_COMMON_ERROR_INSERT_OR_UPDATE;
		}

		//保存Ret_tool_pm_item
		lRc = saveToolPmItem(inTrx, outTrx, pm_item_id);
		if(lRc != _NORMAL){
			return lRc;
		}

		outTrx.setPm_seq_id(pm_seq_id);
		return lRc;
	}

	//批量新增导入的保养计划
	public long saveToolPmSettingFunc2(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		List<MtptoolpmIB> iaryBList = inTrx.getIaryB();
		for(int i = 0; i < iaryBList.size(); i++){
			String pm_seq_id = GUIDGenerator.javaGUID();
			String pm_item_id = GUIDGenerator.javaGUID();
			String tool_model = "";
			//TODO 查询保养项目
			if(!Util.isSpaceCheck(iaryBList.get(i).getTool_id_fk())){
				//根据设备ID获取设备MODEL
				Ret_tool_st tool_st = retToolStDao.get(iaryBList.get(i).getTool_id_fk());
				if(tool_st==null){
					outTrx.setRtn_mesg("找不到设备[" + iaryBList.get(i).getTool_id_fk() + "]的信息[RET_TOOL_ST]");
					return E_RET_TOOL_ST + E_READ_NOT_FOUND;
				}if(Util.isSpaceCheck(tool_st.getTool_run_mode())){
					outTrx.setRtn_mesg("设备[" + iaryBList.get(i).getTool_id_fk() + "]未维护设备运行模式信息[RET_TOOL_ST]");
					return E_MTPPMITEM_NOT_FOUND_TOOL_MODE_SETTING;
				}else{
					tool_model = tool_st.getTool_run_mode();
				}
			}

			String item_hql = "FROM Bis_pm_item where 1=1";
			if(!Util.isSpaceCheck(tool_model)){
				item_hql = item_hql + " and tool_model_fk='" + tool_model + "'";
			}

			if(!Util.isSpaceCheck(iaryBList.get(i).getPm_type())){
				item_hql = item_hql + " and pm_type_fk='" + iaryBList.get(i).getPm_type() + "'";
			}

			List<Bis_pm_item> bisPmItemList = bisPmItemDao.find(item_hql);

			//保存当前日期后一年的设定Ret_tool_pm
			List<Ret_tool_pm> tool_pm_list = new ArrayList<Ret_tool_pm>();
			String[] pm_typ_st = iaryBList.get(i).getPm_type().split("_");//"_"分割;
			String pm_typ = pm_typ_st[0].substring(pm_typ_st[0].length()-1, pm_typ_st[0].length());
			if("Y".equals(pm_typ)){
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Ret_tool_pm tool_pm = new Ret_tool_pm();
//				String from_date = iaryBList.get(i).getPm_start_time();
//				String to_date = iaryBList.get(i).getPm_end_time();
				String shiftIdFk = iaryBList.get(i).getShift_id_fk();
				String from_date ="";
				String to_date ="";
				if("D".equals(shiftIdFk)){
					from_date = iaryBList.get(i).getPm_start_time() + " 08:00:00";
					to_date = iaryBList.get(i).getPm_start_time() + " 20:00:00";
				}else if("N".equals(shiftIdFk)){
					from_date = iaryBList.get(i).getPm_start_time() + " 20:00:00";
					//第二天早上8:00:00
					String tommorrow = Util.getTomorrowData(iaryBList.get(i).getPm_start_time());
					to_date = tommorrow + " 08:00:00";
				}

				if(isSameSetting(from_date, iaryBList.get(i).getTool_id_fk(), iaryBList.get(i).getPm_type(), "")){
					outTrx.setRtn_mesg("设备代码["+ iaryBList.get(i).getTool_id_fk()
							+ "]，[" +from_date+ "]已设定[" + iaryBList.get(i).getPm_type() + "]保养，请检查！");
					return E_MTPTOOLPM_PM_TYP_EXIST;
				}
				tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
				tool_pm.setPm_seq_id(pm_seq_id);
				tool_pm.setPm_item_id(pm_item_id);
				tool_pm.setPm_type(iaryBList.get(i).getPm_type());
				tool_pm.setTool_id_fk(iaryBList.get(i).getTool_id_fk());
				tool_pm.setPm_stat(PROC_WAIT);
				tool_pm.setPm_person_cnt(iaryBList.get(i).getPm_person_cnt());
				tool_pm.setFrom_date(Timestamp.valueOf(from_date));
				tool_pm.setTo_date(Timestamp.valueOf(to_date));
				tool_pm.setLine_id_fk(iaryBList.get(i).getLine_id_fk());
				tool_pm.setMaintenance_master(iaryBList.get(i).getMaintenance_master());
				tool_pm.setShift_id_fk(iaryBList.get(i).getShift_id_fk());
				tool_pm.setPlan_duration(iaryBList.get(i).getPlan_duration());
				tool_pm.setTech_confirm_flg(iaryBList.get(i).getTech_confirm_flg());
				tool_pm.setProd_confirm_flg(iaryBList.get(i).getProd_confirm_flg());
				if("C".equals(iaryBList.get(i).getChange_typ())){//只保存本次保养
					tool_pm.setAlm_id("Y");
				}else {
					tool_pm.setAlm_id("N");
				}
				tool_pm.setAc_pm_delay_flg("N");
				tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
				tool_pm.setEvt_usr(inTrx.getEvt_usr());
				tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
				tool_pm_list.add(tool_pm);
			}else if("Q".equals(pm_typ)){//季度保养
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Integer maxCount = 4 % baseInt == 0 ? 4 / baseInt : 4 / baseInt + 1;
				for(int j =0; j <maxCount; j++){//保存4个季度
					String shiftIdFk = iaryBList.get(i).getShift_id_fk();
					String from_dateString  ="";
					String to_dateString ="";
					if("D".equals(shiftIdFk)){
						from_dateString = iaryBList.get(i).getPm_start_time() + " 08:00:00";
						to_dateString = iaryBList.get(i).getPm_start_time() + " 20:00:00";
					}else if("N".equals(shiftIdFk)){
						from_dateString = iaryBList.get(i).getPm_start_time() + " 20:00:00";
						//第二天早上8:00:00
						String tommorrow = Util.getTomorrowData(iaryBList.get(i).getPm_start_time());
						to_dateString = tommorrow + " 08:00:00";
					}
					Date from_date = Util.getMonthDateAfter(from_dateString,j,3*baseInt,"yyyy-MM-dd HH:mm:ss");
					Date to_date = Util.getMonthDateAfter(to_dateString,j,3*baseInt,"yyyy-MM-dd HH:mm:ss");
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), iaryBList.get(i).getTool_id_fk(), iaryBList.get(i).getPm_type(), "")){
						outTrx.setRtn_mesg("设备代码["+ iaryBList.get(i).getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + iaryBList.get(i).getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					Ret_tool_pm tool_pm = new Ret_tool_pm();
					tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
					tool_pm.setPm_seq_id(pm_seq_id);
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setPm_type(iaryBList.get(i).getPm_type());
					tool_pm.setTool_id_fk(iaryBList.get(i).getTool_id_fk());
					tool_pm.setPm_stat(PROC_WAIT);
					tool_pm.setPm_person_cnt(iaryBList.get(i).getPm_person_cnt());
					tool_pm.setFrom_date(from_date);
					tool_pm.setTo_date(to_date);
					tool_pm.setLine_id_fk(iaryBList.get(i).getLine_id_fk());
					tool_pm.setMaintenance_master(iaryBList.get(i).getMaintenance_master());
					tool_pm.setShift_id_fk(iaryBList.get(i).getShift_id_fk());
					tool_pm.setPlan_duration(iaryBList.get(i).getPlan_duration());
					tool_pm.setTech_confirm_flg(iaryBList.get(i).getTech_confirm_flg());
					tool_pm.setProd_confirm_flg(iaryBList.get(i).getProd_confirm_flg());
					if("C".equals(iaryBList.get(i).getChange_typ())){//只保存本次保养
						tool_pm.setAlm_id("Y");
					}else {
						tool_pm.setAlm_id("N");
					}
					tool_pm.setAc_pm_delay_flg("N");
					tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
					tool_pm.setEvt_usr(inTrx.getEvt_usr());
					tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
					tool_pm_list.add(tool_pm);
					if("C".equals(iaryBList.get(i).getChange_typ())){//只保存本次保养
						break;
					}
				}
			}else if("M".equals(pm_typ)){//月保养
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Integer maxCount = 12 % baseInt == 0 ? 12 / baseInt : 12 / baseInt + 1;
				for(int j =0; j <maxCount; j++){
					String shiftIdFk = iaryBList.get(i).getShift_id_fk();
					String from_dateString  ="";
					String to_dateString ="";
					if("D".equals(shiftIdFk)){
						from_dateString = iaryBList.get(i).getPm_start_time() + " 08:00:00";
						to_dateString = iaryBList.get(i).getPm_start_time() + " 20:00:00";
					}else if("N".equals(shiftIdFk)){
						from_dateString = iaryBList.get(i).getPm_start_time() + " 20:00:00";
						//第二天早上8:00:00
						String tommorrow = Util.getTomorrowData(iaryBList.get(i).getPm_start_time());
						to_dateString = tommorrow + " 08:00:00";
					}

					Date from_date = Util.getMonthDateAfter(from_dateString,j,baseInt,"yyyy-MM-dd HH:mm:ss");
					Date to_date = Util.getMonthDateAfter(to_dateString,j,baseInt,"yyyy-MM-dd HH:mm:ss");
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), iaryBList.get(i).getTool_id_fk(), iaryBList.get(i).getPm_type(), "")){
						outTrx.setRtn_mesg("设备代码["+ iaryBList.get(i).getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + iaryBList.get(i).getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					Ret_tool_pm tool_pm = new Ret_tool_pm();
					tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
					tool_pm.setPm_seq_id(pm_seq_id);
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setPm_type(iaryBList.get(i).getPm_type());
					tool_pm.setTool_id_fk(iaryBList.get(i).getTool_id_fk());
					tool_pm.setPm_stat(PROC_WAIT);
					tool_pm.setPm_person_cnt(iaryBList.get(i).getPm_person_cnt());
					Timestamp fromDate = new Timestamp(from_date.getTime());
					Timestamp toDate = new Timestamp(to_date.getTime());
					tool_pm.setFrom_date(fromDate);
					tool_pm.setTo_date(toDate);
					if("C".equals(inTrx.getChange_typ())){//只保存本次保养
						tool_pm.setAlm_id("Y");
					}else {
						tool_pm.setAlm_id("N");
					}
					tool_pm.setAc_pm_delay_flg("N");
					tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
					tool_pm.setEvt_usr(inTrx.getEvt_usr());
					tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
					tool_pm.setLine_id_fk(iaryBList.get(i).getLine_id_fk());
					tool_pm.setMaintenance_master(iaryBList.get(i).getMaintenance_master());
					tool_pm.setShift_id_fk(iaryBList.get(i).getShift_id_fk());
					tool_pm.setPlan_duration(iaryBList.get(i).getPlan_duration());
					tool_pm.setTech_confirm_flg(iaryBList.get(i).getTech_confirm_flg());
					tool_pm.setProd_confirm_flg(iaryBList.get(i).getProd_confirm_flg());
					tool_pm_list.add(tool_pm);
					if("C".equals(iaryBList.get(i).getChange_typ())){//只保存本次保养
						break;
					}
				}
			}else if("W".equals(pm_typ)){//周保养
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Integer maxCount = 52 % baseInt == 0 ? 52 / baseInt : 52 / baseInt + 1;
				for(int j=0; j<maxCount; j++){
					String shiftIdFk = iaryBList.get(i).getShift_id_fk();
					String from_dateString  ="";
					String to_dateString ="";
					if("D".equals(shiftIdFk)){
						from_dateString = iaryBList.get(i).getPm_start_time() + " 08:00:00";
						to_dateString = iaryBList.get(i).getPm_start_time() + " 20:00:00";
					}else if("N".equals(shiftIdFk)){
						from_dateString = iaryBList.get(i).getPm_start_time() + " 20:00:00";
						//第二天早上8:00:00
						String tommorrow = Util.getTomorrowData(iaryBList.get(i).getPm_start_time());
						to_dateString = tommorrow + " 08:00:00";
					}
					Date from_date = Util.getWeekOfYearDateAfter(from_dateString,j,baseInt,"yyyy-MM-dd HH:mm:ss");
					Date to_date = Util.getWeekOfYearDateAfter(to_dateString,j,baseInt,"yyyy-MM-dd HH:mm:ss");
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), iaryBList.get(i).getTool_id_fk(), iaryBList.get(i).getPm_type(), "")){
						outTrx.setRtn_mesg("设备代码["+ iaryBList.get(i).getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + iaryBList.get(i).getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					Ret_tool_pm tool_pm = new Ret_tool_pm();
					tool_pm.setEvt_seq_id(GUIDGenerator.javaGUID());
					tool_pm.setPm_seq_id(pm_seq_id);
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setPm_type(iaryBList.get(i).getPm_type());
					tool_pm.setTool_id_fk(iaryBList.get(i).getTool_id_fk());
					tool_pm.setPm_stat(PROC_WAIT);
					tool_pm.setPm_person_cnt(iaryBList.get(i).getPm_person_cnt());
					Timestamp fromDate = new Timestamp(from_date.getTime());
					Timestamp toDate = new Timestamp(to_date.getTime());
					tool_pm.setFrom_date(fromDate);
					tool_pm.setTo_date(toDate);
					if("C".equals(iaryBList.get(i).getChange_typ())){//只保存本次保养
						tool_pm.setAlm_id("Y");
					}else {
						tool_pm.setAlm_id("N");
					}
					tool_pm.setAc_pm_delay_flg("N");
					tool_pm.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
					tool_pm.setEvt_usr(inTrx.getEvt_usr());
					tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
					tool_pm.setLine_id_fk(iaryBList.get(i).getLine_id_fk());
					tool_pm.setMaintenance_master(iaryBList.get(i).getMaintenance_master());
					tool_pm.setShift_id_fk(iaryBList.get(i).getShift_id_fk());
					tool_pm.setPlan_duration(iaryBList.get(i).getPlan_duration());
					tool_pm.setTech_confirm_flg(iaryBList.get(i).getTech_confirm_flg());
					tool_pm.setProd_confirm_flg(iaryBList.get(i).getProd_confirm_flg());
					tool_pm_list.add(tool_pm);
					if("C".equals(iaryBList.get(i).getChange_typ())){//只保存本次保养
						break;
					}
				}
			}else{
				outTrx.setRtn_mesg("除年保养(Y)、季度保养(Q)、月保养(M)、周保养(W)及这四种类型的整数倍保养如(2W、2Q、2M等等)，其他保养类型暂不支持，请联系系统开发人员！");
				return E_MTPTOOLPM_INVALID_PM_TYPE;
			}

			try {
				retToolPmDao.saveOrUpdateAll(tool_pm_list);
			} catch (Exception e) {
				outTrx.setRtn_mesg(e.getCause().getMessage());
				return E_COMMON_ERROR_INSERT_OR_UPDATE;
			}

			//保存Ret_tool_pm_item
			lRc = saveToolPmItem2(inTrx, outTrx, pm_item_id,bisPmItemList,iaryBList.get(i));
			if(lRc != _NORMAL){
				return lRc;
			}
		}

		return lRc;
	}


	/**
	 * 更新计划
	 */
	public long updateToolPmSettingFunc(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		//检查保养项目
		if(inTrx.getIaryA().isEmpty()){
			outTrx.setRtn_mesg("未设定保养项目，请确认！");
			return E_MTPTOOLPM_INVALID_INPUT;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		String pm_item_id = GUIDGenerator.javaGUID();
		String oldShiftIdFk = inTrx.getOld_shift_id_fk();
		String shiftIdFk = inTrx.getShift_id_fk();
		String plan_duration = inTrx.getPlan_duration();
		String maintenance_master = inTrx.getMaintenance_master();
		String tech_confirm_flg = inTrx.getTech_confirm_flg();
		String prod_confirm_flg = inTrx.getProd_confirm_flg();

		String old_from_date ="";
		String old_to_date ="";
		if("D".equals(oldShiftIdFk)){
			old_from_date =inTrx.getFrom_date() + " 08:00:00";
			old_to_date = inTrx.getFrom_date() + " 20:00:00";
		}else if("N".equals(oldShiftIdFk)){
			old_from_date = inTrx.getFrom_date()  + " 20:00:00";
			//第二天早上8:00:00
			String tommorrow = Util.getTomorrowData(inTrx.getFrom_date());
			old_to_date = tommorrow + " 08:00:00";
		}
		//更新Ret_tool_pm
		String hql_tool_pm="From Ret_tool_pm where 1=1 and tool_id_fk='" + inTrx.getTool_id_fk()
				+ "' and pm_seq_id='" + inTrx.getPm_seq_id()
				+ "' and pm_stat<>'" + PROC_COMPLETE + "'";
		if("C".equals(inTrx.getChange_typ())){//更新本次
			hql_tool_pm +=" and from_date= '" + Timestamp.valueOf(old_from_date)
					+ "' and to_date = '"+Timestamp.valueOf(old_to_date) + "' and pm_type='" + inTrx.getPm_type() + "'";
		}
		hql_tool_pm += " order by from_date asc";
		List<Ret_tool_pm> tool_pm_list = retToolPmDao.find(hql_tool_pm);

		String[] pm_typ_st = inTrx.getPm_type().split("_");//"_"分割;
		String pm_typ = pm_typ_st[0].substring(pm_typ_st[0].length()-1, pm_typ_st[0].length());

		if(!tool_pm_list.isEmpty()){
			for(int i=0; i<tool_pm_list.size(); i++){
				Ret_tool_pm tool_pm = tool_pm_list.get(i);
				if("C".equals(inTrx.getChange_typ())){//更新本次
					tool_pm.setAlm_id("Y");
				}else {
					tool_pm.setAlm_id("N");
				}
				if("Y".equals(pm_typ)){
					Integer baseInt = pm_typ_st[0].length() == 1 ?
							1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
					Date from_date, to_date;

					if(!StringUtils.isEmpty(inTrx.getPm_start_time())){
						String from_dateString  ="";
						String to_dateString ="";
						if("D".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time() + " 08:00:00";
							to_dateString = inTrx.getPm_start_time()  + " 20:00:00";
						}else if("N".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time()  + " 20:00:00";
							//第二天早上8:00:00
							String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
							to_dateString = tommorrow + " 08:00:00";
						}
						 from_date = Util.getYearDateAfter(from_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
						 to_date = Util.getYearDateAfter(to_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
					}else{
						 from_date = Util.getYearDateAfter(old_from_date,i,baseInt,"yyyy-MM-dd HH:mm:ss");
						 to_date = Util.getYearDateAfter(old_to_date,i,baseInt,"yyyy-MM-dd HH:mm:ss");
					}
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), tool_pm.getPm_seq_id())){
						outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setFrom_date(from_date);
					tool_pm.setTo_date(to_date);
					tool_pm.setShift_id_fk(shiftIdFk);
					tool_pm.setPlan_duration(plan_duration);
					tool_pm.setMaintenance_master(maintenance_master);
					tool_pm.setTech_confirm_flg(tech_confirm_flg);
					tool_pm.setProd_confirm_flg(prod_confirm_flg);
				}else if("Q".equals(pm_typ)){
					Integer baseInt = pm_typ_st[0].length() == 1 ?
							1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
					Date from_date, to_date;
					if(!StringUtils.isEmpty(inTrx.getPm_start_time())){
						String from_dateString  ="";
						String to_dateString ="";
						if("D".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time() + " 08:00:00";
							to_dateString = inTrx.getPm_start_time() + " 20:00:00";
						}else if("N".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time() + " 20:00:00";
							//第二天早上8:00:00
							String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
							to_dateString = tommorrow + " 08:00:00";
						}
						 from_date = Util.getMonthDateAfter(from_dateString,i,3*baseInt,"yyyy-MM-dd HH:mm:ss");
						 to_date = Util.getMonthDateAfter(to_dateString,i,3*baseInt,"yyyy-MM-dd HH:mm:ss");
					}else{
						 from_date = Util.getMonthDateAfter(old_from_date,i,3*baseInt,"yyyy-MM-dd HH:mm:ss");
						 to_date = Util.getMonthDateAfter(old_to_date,i,3*baseInt,"yyyy-MM-dd HH:mm:ss");
					}
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), tool_pm.getPm_seq_id())){
						outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setFrom_date(from_date);
					tool_pm.setTo_date(to_date);
					tool_pm.setShift_id_fk(shiftIdFk);
					tool_pm.setPlan_duration(plan_duration);
					tool_pm.setMaintenance_master(maintenance_master);
					tool_pm.setTech_confirm_flg(tech_confirm_flg);
					tool_pm.setProd_confirm_flg(prod_confirm_flg);
				}else if("M".equals(pm_typ)){
					Integer baseInt = pm_typ_st[0].length() == 1 ?
							1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
					Date from_date, to_date;
					if(!StringUtils.isEmpty(inTrx.getPm_start_time())){
						String from_dateString  ="";
						String to_dateString ="";
						if("D".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time()  + " 08:00:00";
							to_dateString = inTrx.getPm_start_time() + " 20:00:00";
						}else if("N".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time() + " 20:00:00";
							//第二天早上8:00:00
							String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
							to_dateString = tommorrow + " 08:00:00";
						}
						from_date = Util.getMonthDateAfter(from_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
						to_date = Util.getMonthDateAfter(to_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
					}else{
						from_date = Util.getMonthDateAfter(old_from_date,i,baseInt,"yyyy-MM-dd HH:mm:ss");
						to_date = Util.getMonthDateAfter(old_to_date,i,baseInt,"yyyy-MM-dd HH:mm:ss");
					}
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), tool_pm.getPm_seq_id())){
						outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setFrom_date(from_date);
					tool_pm.setTo_date(to_date);
					tool_pm.setShift_id_fk(shiftIdFk);
					tool_pm.setPlan_duration(plan_duration);
					tool_pm.setMaintenance_master(maintenance_master);
					tool_pm.setTech_confirm_flg(tech_confirm_flg);
					tool_pm.setProd_confirm_flg(prod_confirm_flg);
				}else if("W".equals(pm_typ)){
					Integer baseInt = pm_typ_st[0].length() == 1 ?
							1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
					Date from_date, to_date;
					if(!StringUtils.isEmpty(inTrx.getPm_start_time())){
						String from_dateString  ="";
						String to_dateString ="";
						if("D".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time() + " 08:00:00";
							to_dateString = inTrx.getPm_start_time() + " 20:00:00";
						}else if("N".equals(shiftIdFk)){
							from_dateString = inTrx.getPm_start_time() + " 20:00:00";
							//第二天早上8:00:00
							String tommorrow = Util.getTomorrowData(inTrx.getPm_start_time());
							to_dateString = tommorrow + " 08:00:00";
						}
						from_date = Util.getWeekOfYearDateAfter(from_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
						to_date = Util.getWeekOfYearDateAfter(to_dateString,i,baseInt,"yyyy-MM-dd HH:mm:ss");
					}else{
						from_date = Util.getWeekOfYearDateAfter(old_from_date,i,baseInt,"yyyy-MM-dd HH:mm:ss");
						to_date = Util.getWeekOfYearDateAfter(old_to_date,i,baseInt,"yyyy-MM-dd HH:mm:ss");
					}
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), inTrx.getTool_id_fk(), inTrx.getPm_type(), tool_pm.getPm_seq_id())){
						outTrx.setRtn_mesg("设备代码["+ inTrx.getTool_id_fk()
								+ "]，[" + Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss") + "]已设定[" + inTrx.getPm_type() + "]保养，请检查！");
						return E_MTPTOOLPM_PM_TYP_EXIST;
					}
					tool_pm.setPm_item_id(pm_item_id);
					tool_pm.setFrom_date(from_date);
					tool_pm.setTo_date(to_date);
					tool_pm.setShift_id_fk(shiftIdFk);
					tool_pm.setPlan_duration(plan_duration);
					tool_pm.setMaintenance_master(maintenance_master);
					tool_pm.setTech_confirm_flg(tech_confirm_flg);
					tool_pm.setProd_confirm_flg(prod_confirm_flg);
				}else{
					outTrx.setRtn_mesg("除年保养(Y)、季度保养(Q)、月保养(M)、周保养(W)及这四种类型的整数倍保养如(2W、2Q、2M等等)，其他保养类型暂不支持，请联系系统开发人员！");
					return E_MTPTOOLPM_INVALID_PM_TYPE;
				}

				tool_pm.setEvt_usr(inTrx.getEvt_usr());
				tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
				tool_pm.setEvt_cate(EVT_TOOL_PM_UPDATE);
			}

			try {
				retToolPmDao.saveOrUpdateAll(tool_pm_list);
			} catch (Exception e) {
				outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
				outTrx.setRtn_mesg(e.getCause().getMessage());
				return E_COMMON_ERROR_INSERT_OR_UPDATE;
			}
		}else{
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			return lRc;
		}

		//保存Ret_tool_pm_item
		lRc = saveToolPmItem(inTrx, outTrx, pm_item_id);
		if(lRc != _NORMAL){
			return lRc;
		}
		return lRc;
	}

	/**
	 * 删除保养计划
	 */
	public long  deleteToolPmSettingFunc(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		List<MtptoolpmOA> oaryAList = new ArrayList<MtptoolpmOA>();
		String hql_tool_pm="From Ret_tool_pm where 1=1 and tool_id_fk='" + inTrx.getTool_id_fk()
				+ "' and pm_seq_id='" + inTrx.getPm_seq_id()
				+ "' and pm_stat<>'" + PROC_COMPLETE + "'";
		String shiftIdFk = inTrx.getShift_id_fk();
		String time = "";
		if("D".equals(shiftIdFk)){
			time = "08:00:00";
		}else{
			time = "20:00:00";
		}
		if("C".equals(inTrx.getChange_typ())){//更新本次
			hql_tool_pm +=" and from_date= '" + inTrx.getFrom_date() +" "+time
					+ "'and pm_type='" + inTrx.getPm_type() + "'";
		}
		List<Ret_tool_pm> tool_pm_list = retToolPmDao.find(hql_tool_pm);
		if(!tool_pm_list.isEmpty()){
			for(Ret_tool_pm tool_pm:tool_pm_list){
				if(PROC_IN_PROCESS.equals(tool_pm.getPm_stat()) && "C".equals(inTrx.getChange_typ())){
					outTrx.setRtn_mesg("本次保养计划已经开始，无法删除！");
					return E_MTPTOOLPM_PM_STATUS_INPR;
				}else if(PROC_WAIT.equals(tool_pm.getPm_stat())){//删除WAIT状态的计划
					try {
						tool_pm.setEvt_cate(EVT_TOOL_PM_DELETE);
						tool_pm.setEvt_usr(inTrx.getEvt_usr());
						tool_pm.setEvt_timestamp(Util.getCurrentTimestamp());
						retToolPmDao.delete(tool_pm);
					} catch (Exception e) {
						outTrx.setRtn_mesg(e.getCause().getMessage());
						return E_COMMON_ERROR_DELETE;
					}
				}
			}

			//获取保养计划周期的第一个设定计划
			String sql_tool_pm="SELECT PM_SEQ_ID,PM_TYPE,TOOL_ID_FK,MIN(FROM_DATE) AS PM_DATE FROM RET_TOOL_PM WHERE PM_STAT<>'COMP' "
					+ " AND TOOL_ID_FK='" + inTrx.getTool_id_fk()
					+ "' AND PM_SEQ_ID='" + inTrx.getPm_seq_id()
					+ "' AND PM_TYPE='" + inTrx.getPm_type()
					+ "' GROUP BY PM_SEQ_ID,PM_TYPE,TOOL_ID_FK ORDER BY PM_DATE,TOOL_ID_FK";
			List<Object[]> objList  =  retToolPmDao.findBySQL(sql_tool_pm);
			for(int i=0; i<objList.size(); i++){
				Object[] obj = objList.get(i);
				MtptoolpmOA oaryA = new MtptoolpmOA();
				oaryA.setFrom_date(obj[3].toString().substring(0, 10));
				oaryAList.add(oaryA);
			}
		}else{
			outTrx.setRtn_mesg("未找到设备代码[" + inTrx.getTool_id_fk()
					+ "][" + inTrx.getFrom_date()
					+ "][" + inTrx.getPm_type() + "]保养计划，无需删除！");
			return E_MTPTOOLPM_PM_STATUS_INPR;
		}
		outTrx.setOaryA(oaryAList);
		return lRc;
	}

	public long  saveToolPmListFunc(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		Timestamp gEvtTimestamp = Util.getCurrentTimestamp();
		List<MtptoolpmOA> oaryAList = new ArrayList<MtptoolpmOA>();
		String evt_seq_id = inTrx.getEvt_seq_id();
		Ret_tool_pm ret_tool_pm = retToolPmDao.get(evt_seq_id);
		if(ret_tool_pm==null){
			outTrx.setRtn_mesg("找不到保养设定！");
			return E_RET_TOOL_PM + E_READ_NOT_FOUND;
		}
		if(PROC_WAIT.equals(ret_tool_pm.getPm_stat())){
			outTrx.setRtn_mesg("本次保养未开始，不允许保存结果，请确认！");
			return E_XPTOOLPM_PM_STATUS_WAIT;
		}
		if(PROC_COMPLETE.equals(ret_tool_pm.getPm_stat())){
			outTrx.setRtn_mesg("本次保养已完成，不允许重复保养，请确认！");
			return E_XPTOOLPM_PM_STATUS_COMP;
		}
		//新增tool_pm_list
		List<Ret_tool_pm_list> tool_pm_list_list = new ArrayList<Ret_tool_pm_list>();
		for(MtptoolpmIA iaryA : inTrx.getIaryA()){
			Ret_tool_pm_list pm_list = new Ret_tool_pm_list();
			pm_list.setEvt_seq_id(GUIDGenerator.javaGUID());
			pm_list.setPm_evt_seq_id(ret_tool_pm.getEvt_seq_id());
			pm_list.setTool_id_fk(ret_tool_pm.getTool_id_fk());
			pm_list.setData_dsc(iaryA.getData_dsc());
			pm_list.setData_value(iaryA.getData_value());
			if(!Util.isSpaceCheck(iaryA.getL_spec())){
				pm_list.setL_spec_fk(Double.valueOf(iaryA.getL_spec()));
			}else{
				pm_list.setL_spec_fk(null);
			}
			if(!Util.isSpaceCheck(iaryA.getU_spec())){
				pm_list.setU_spec_fk(Double.valueOf(iaryA.getU_spec()));
			}else{
				pm_list.setU_spec_fk(null);
			}
			pm_list.setEvt_usr(inTrx.getEvt_usr());
			pm_list.setEvt_timestamp(gEvtTimestamp);
			pm_list.setAc_pm_note(iaryA.getAc_pm_note());
			//维护人
			pm_list.setMaintenance_man(iaryA.getMaintenance_man());
			tool_pm_list_list.add(pm_list);
		}
		retToolPmListDao.saveOrUpdateAll(tool_pm_list_list);
		//更新Ret_tool_pm信息
		if(this.isDealy(ret_tool_pm.getTo_date().toString())){
			ret_tool_pm.setAc_pm_delay_flg("Y");
		}
		ret_tool_pm.setPm_stat(PROC_COMPLETE);
		ret_tool_pm.setAc_pm_end_timestamp(gEvtTimestamp);
		ret_tool_pm.setEvt_cate(EVT_TOOL_PM_END);
		ret_tool_pm.setEvt_timestamp(gEvtTimestamp);
		ret_tool_pm.setEvt_usr(inTrx.getEvt_usr());
		ret_tool_pm.setTool_pm_usr(inTrx.getEvt_usr());
		ret_tool_pm.setEqt_confirm_per(inTrx.getEqt_confirm_per());
		ret_tool_pm.setPro_confirm_per(inTrx.getPro_confirm_per());
		ret_tool_pm.setTech_confirm_per(inTrx.getTech_confirm_per());
		ret_tool_pm.setAssistants(inTrx.getAssistants());
		ret_tool_pm.setAc_pm_note(inTrx.getAc_pm_note());
		retToolPmDao.update(ret_tool_pm);

       /*******检查当前执行的保养是否是保养周期的最后一次保养*****/
		List<Ret_tool_pm> ret_tool_list = retToolPmDao.find("FROM Ret_tool_pm WHERE pm_seq_id='" + ret_tool_pm.getPm_seq_id()
				+ "' AND from_date > '" + ret_tool_pm.getFrom_date().toString()+"' AND pm_stat='WAIT'");
		if(ret_tool_list.size() == 0){
			//保存当前日期后一年的设定Ret_tool_pm
			List<Ret_tool_pm> tool_pm_list2 = new ArrayList<Ret_tool_pm>();
			String[] pm_typ_st = ret_tool_pm.getPm_type().split("_");//"_"分割;
			String pm_typ = pm_typ_st[0].substring(pm_typ_st[0].length()-1, pm_typ_st[0].length());
			if("Y".equals(pm_typ)){
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Ret_tool_pm tool_pm_new = new Ret_tool_pm();
				Date from_date = Util.getYearDateAfter(ret_tool_pm.getFrom_date().toString(),1,baseInt,"yyyy-MM-dd HH:mm:ss");
				Date to_date = Util.getYearDateAfter(ret_tool_pm.getTo_date().toString(),1,baseInt,"yyyy-MM-dd HH:mm:ss");
				if(!isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), ret_tool_pm.getTool_id_fk(), ret_tool_pm.getPm_type(), ret_tool_pm.getPm_seq_id())){
					if(_NO.equals(ret_tool_pm.getAlm_id())){
						tool_pm_new.setEvt_seq_id(GUIDGenerator.javaGUID());
						tool_pm_new.setPm_seq_id(ret_tool_pm.getPm_seq_id());
						tool_pm_new.setPm_item_id(ret_tool_pm.getPm_item_id());
						tool_pm_new.setPm_type(ret_tool_pm.getPm_type());
						tool_pm_new.setTool_id_fk(ret_tool_pm.getTool_id_fk());
						tool_pm_new.setPm_stat(PROC_WAIT);
						tool_pm_new.setFrom_date(from_date);
						tool_pm_new.setTo_date(to_date);
						tool_pm_new.setAlm_id(ret_tool_pm.getAlm_id());
						tool_pm_new.setAc_pm_delay_flg("N");
						tool_pm_new.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
						tool_pm_new.setEvt_usr(ret_tool_pm.getEvt_usr());
						tool_pm_new.setEvt_timestamp(gEvtTimestamp);
						tool_pm_list2.add(tool_pm_new);
					}

				}
			}else if("Q".equals(pm_typ)){//季度保养
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Integer maxCount = 4 % baseInt == 0 ? 4 / baseInt : 4 / baseInt + 1;
				for(int i=0; i<maxCount; i++){//保存4个季度
					Date from_date = Util.getMonthDateAfter(ret_tool_pm.getFrom_date().toString(),i+1,3*baseInt,"yyyy-MM-dd HH:mm:ss");
					Date to_date = Util.getMonthDateAfter(ret_tool_pm.getTo_date().toString(),i+1,3*baseInt,"yyyy-MM-dd HH:mm:ss");
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), ret_tool_pm.getTool_id_fk(), ret_tool_pm.getPm_type(), ret_tool_pm.getPm_seq_id())){
						continue;
					}
					if(_NO.equals(ret_tool_pm.getAlm_id())) {
						Ret_tool_pm tool_pm_new = new Ret_tool_pm();
						tool_pm_new.setEvt_seq_id(GUIDGenerator.javaGUID());
						tool_pm_new.setPm_seq_id(ret_tool_pm.getPm_seq_id());
						tool_pm_new.setPm_item_id(ret_tool_pm.getPm_item_id());
						tool_pm_new.setPm_type(ret_tool_pm.getPm_type());
						tool_pm_new.setTool_id_fk(ret_tool_pm.getTool_id_fk());
						tool_pm_new.setPm_stat(PROC_WAIT);
						tool_pm_new.setFrom_date(from_date);
						tool_pm_new.setTo_date(to_date);
						tool_pm_new.setAlm_id(ret_tool_pm.getAlm_id());
						tool_pm_new.setAc_pm_delay_flg("N");
						tool_pm_new.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
						tool_pm_new.setEvt_usr(ret_tool_pm.getEvt_usr());
						tool_pm_new.setEvt_timestamp(gEvtTimestamp);
						tool_pm_list2.add(tool_pm_new);
					}
				}
			}else if("M".equals(pm_typ)){//月保养
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Integer maxCount = 12 % baseInt == 0 ? 12 / baseInt : 12 / baseInt + 1;
				for(int i=0; i<maxCount; i++){
					Date from_date = Util.getMonthDateAfter(ret_tool_pm.getFrom_date().toString(),i+1,baseInt,"yyyy-MM-dd HH:mm:ss");
					Date to_date = Util.getMonthDateAfter(ret_tool_pm.getTo_date().toString(),i+1,baseInt,"yyyy-MM-dd HH:mm:ss");
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), ret_tool_pm.getTool_id_fk(), ret_tool_pm.getPm_type(), ret_tool_pm.getPm_seq_id())){
						continue;
					}
					if(_NO.equals(ret_tool_pm.getAlm_id())) {
						Ret_tool_pm tool_pm_new = new Ret_tool_pm();
						tool_pm_new.setEvt_seq_id(GUIDGenerator.javaGUID());
						tool_pm_new.setPm_seq_id(ret_tool_pm.getPm_seq_id());
						tool_pm_new.setPm_item_id(ret_tool_pm.getPm_item_id());
						tool_pm_new.setPm_type(ret_tool_pm.getPm_type());
						tool_pm_new.setTool_id_fk(ret_tool_pm.getTool_id_fk());
						tool_pm_new.setPm_stat(PROC_WAIT);
						tool_pm_new.setFrom_date(from_date);
						tool_pm_new.setTo_date(to_date);
						tool_pm_new.setAlm_id(ret_tool_pm.getAlm_id());
						tool_pm_new.setAc_pm_delay_flg("N");
						tool_pm_new.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
						tool_pm_new.setEvt_usr(ret_tool_pm.getEvt_usr());
						tool_pm_new.setEvt_timestamp(gEvtTimestamp);
						tool_pm_list2.add(tool_pm_new);
					}
				}
			}else if("W".equals(pm_typ)){//周保养
				Integer baseInt = pm_typ_st[0].length() == 1 ?
						1 : Integer.valueOf(pm_typ_st[0].substring(0, pm_typ_st[0].length()-1)); //长度为1,基数为1；否则基数为剔除后一位后得到的整数
				Integer maxCount = 52 % baseInt == 0 ? 52 / baseInt : 52 / baseInt + 1;
				for(int i=0; i<maxCount; i++){
					Date from_date = Util.getWeekOfYearDateAfter(ret_tool_pm.getFrom_date().toString(),i+1,baseInt,"yyyy-MM-dd HH:mm:ss");
					Date to_date = Util.getWeekOfYearDateAfter(ret_tool_pm.getTo_date().toString(),i+1,baseInt,"yyyy-MM-dd HH:mm:ss");
					if(isSameSetting(Util.Date2String(from_date,"yyyy-MM-dd HH:mm:ss"), ret_tool_pm.getTool_id_fk(), ret_tool_pm.getPm_type(), ret_tool_pm.getPm_seq_id())){
						continue;
					}
					if(_NO.equals(ret_tool_pm.getAlm_id())) {
						Ret_tool_pm tool_pm_new = new Ret_tool_pm();
						tool_pm_new.setEvt_seq_id(GUIDGenerator.javaGUID());
						tool_pm_new.setPm_seq_id(ret_tool_pm.getPm_seq_id());
						tool_pm_new.setPm_item_id(ret_tool_pm.getPm_item_id());
						tool_pm_new.setPm_type(ret_tool_pm.getPm_type());
						tool_pm_new.setTool_id_fk(ret_tool_pm.getTool_id_fk());
						tool_pm_new.setPm_stat(PROC_WAIT);
						tool_pm_new.setFrom_date(from_date);
						tool_pm_new.setTo_date(to_date);
						tool_pm_new.setAlm_id(ret_tool_pm.getAlm_id());
						tool_pm_new.setAc_pm_delay_flg("N");
						tool_pm_new.setEvt_cate(EVT_TOOL_PM_SETTING);//保养设定
						tool_pm_new.setEvt_usr(ret_tool_pm.getEvt_usr());
						tool_pm_new.setEvt_timestamp(gEvtTimestamp);
						tool_pm_list2.add(tool_pm_new);
					}
				}
			}else{
				outTrx.setRtn_mesg("除年保养(Y)、季度保养(Q)、月保养(M)、周保养(W)及这四种类型的整数倍保养如(2W、2Q、2M等等)，其他保养类型暂不支持，请联系系统开发人员！");
				return E_XPTOOLPM_PM_TYPE;
			}
			try {
				if(tool_pm_list2.size() > 0){
					retToolPmDao.saveOrUpdateAll(tool_pm_list2);
				}
			} catch (Exception e) {
				outTrx.setRtn_mesg(e.getCause().getMessage());
				return E_XPTOOLPM_PM_SAVE_EORR;
			}

			FtptolopeO ftptolopeO = new FtptolopeO();
			try {

				ftptolopeO = updatetool_stat(ret_tool_pm.getTool_id_fk());
				if (!ftptolopeO.getRtn_code().equals(RETURN_CODE_OK)) {
					String gszMsgBuf = ftptolopeO.getRtn_mesg();
					outTrx.setRtn_code(ftptolopeO.getRtn_code());
					outTrx.setRtn_mesg(gszMsgBuf);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return lRc;
	}

	//保存导入计划周期的保养项目
	public long saveToolPmItem2(MtptoolpmI inTrx, MtptoolpmO outTrx, String pm_item_id,List<Bis_pm_item> bisPmItemList,MtptoolpmIB iaryB){
		long lRc = _NORMAL;
		//保存Ret_tool_pm_item
		List<Ret_tool_pm_item> tool_pm_item_list = new ArrayList<Ret_tool_pm_item>();
		for(int i = 0; i < bisPmItemList.size(); i++){
			Ret_tool_pm_item tool_pm_item = new Ret_tool_pm_item();
			tool_pm_item.setEvt_seq_id(GUIDGenerator.javaGUID());
			tool_pm_item.setPm_item_id_fk(pm_item_id);
			tool_pm_item.setTool_id_fk(iaryB.getTool_id_fk());
			tool_pm_item.setData_dsc(bisPmItemList.get(i).getId().getData_dsc());
			tool_pm_item.setL_spec(bisPmItemList.get(i).getL_spec());
			tool_pm_item.setU_spec(bisPmItemList.get(i).getU_spec());
			tool_pm_item.setPm_note(bisPmItemList.get(i).getPm_note());
			tool_pm_item.setEvt_usr(inTrx.getEvt_usr());
			tool_pm_item.setEvt_timestamp(Util.getCurrentTimestamp());
			tool_pm_item.setData_typ(bisPmItemList.get(i).getData_typ());
			tool_pm_item.setData_cnt(bisPmItemList.get(i).getData_cnt());
			tool_pm_item_list.add(tool_pm_item);
		}

		try {
			retToolPmItemDao.saveOrUpdateAll(tool_pm_item_list);
		} catch (Exception e) {
			outTrx.setRtn_mesg(e.getCause().getMessage());
			return E_COMMON_ERROR_INSERT_OR_UPDATE;
		}
		return lRc;
	}



	/**
	 * 保存设备保养周期中的保养项目
	 * @param inTrx
	 * @param outTrx
	 * @param pm_item_id
	 * @return
	 */
	public long saveToolPmItem(MtptoolpmI inTrx, MtptoolpmO outTrx, String pm_item_id){
		long lRc = _NORMAL;
		//保存Ret_tool_pm_item
		List<Ret_tool_pm_item> tool_pm_item_list = new ArrayList<Ret_tool_pm_item>();
		for(MtptoolpmIA iary:inTrx.getIaryA()){
			Ret_tool_pm_item tool_pm_item = new Ret_tool_pm_item();
			tool_pm_item.setEvt_seq_id(GUIDGenerator.javaGUID());
			tool_pm_item.setPm_item_id_fk(pm_item_id);
			tool_pm_item.setTool_id_fk(inTrx.getTool_id_fk());
			tool_pm_item.setData_dsc(iary.getData_dsc());
			if(!Util.isSpaceCheck(iary.getL_spec())){
				tool_pm_item.setL_spec(Double.valueOf(iary.getL_spec()));
			}else{
				tool_pm_item.setL_spec(null);
			}
			if(!Util.isSpaceCheck(iary.getU_spec())){
				tool_pm_item.setU_spec(Double.valueOf(iary.getU_spec()));
			}else{
				tool_pm_item.setU_spec(null);
			}
            tool_pm_item.setPm_note(iary.getPm_note());
			tool_pm_item.setEvt_usr(inTrx.getEvt_usr());
			tool_pm_item.setEvt_timestamp(Util.getCurrentTimestamp());
			tool_pm_item.setData_typ(iary.getData_typ());
			tool_pm_item.setData_cnt(iary.getData_cnt());
			tool_pm_item_list.add(tool_pm_item);
		}

		try {
			retToolPmItemDao.saveOrUpdateAll(tool_pm_item_list);
		} catch (Exception e) {
			outTrx.setRtn_mesg(e.getCause().getMessage());
			return E_COMMON_ERROR_INSERT_OR_UPDATE;
		}
		return lRc;
	}
	public long queryToolPmByToolId(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		     String toolId = inTrx.getTool_id_fk();
		     String hql = "From Ret_tool_pm where tool_id_fk='" +toolId+"' and pm_stat='"+PROC_WAIT+"' order by from_date ";
		     List<Ret_tool_pm> ret_tool_pms = retToolPmDao.find(hql);
		     List<MtptoolpmOA> oaryList = new ArrayList<>();
		     for(Ret_tool_pm ret_tool_pm : ret_tool_pms){
				 MtptoolpmOA   oary = new MtptoolpmOA();
                 String hqlM ="From Ret_tool_pm_item where pm_item_id_fk='" +ret_tool_pm.getPm_item_id()+"'";
                 List<Ret_tool_pm_item> ret_tool_pm_items = retToolPmItemDao.find(hqlM);
				 oary.setEvt_seq_id(ret_tool_pm.getEvt_seq_id());
				 oary.setFrom_date(ret_tool_pm.getFrom_date().toString().substring(0,10));
				 oary.setPm_type_fk(ret_tool_pm.getPm_type());
				 oary.setPm_desc(oary.getFrom_date()+":"+ret_tool_pm_items.get(0).getData_dsc());
				 oaryList.add(oary);
			 }
		outTrx.setOaryA(oaryList);
		return lRc;
	}

	public long queryToolPmByEvtId(MtptoolpmI inTrx, MtptoolpmO outTrx){
		long lRc = _NORMAL;
		String evt_seq_id = inTrx.getEvt_seq_id();
		Ret_tool_pm ret_tool_pm = retToolPmDao.get(evt_seq_id);
		if(ret_tool_pm==null){
			outTrx.setRtn_mesg("找不到保养设定！");
			return E_RET_TOOL_PM + E_READ_NOT_FOUND;
		}
		String techConfirmFlg = ret_tool_pm.getTech_confirm_flg();
		String prodCinfirmFlg = ret_tool_pm.getProd_confirm_flg();
		List<MtptoolpmOA> oaryAlist = new ArrayList<>();
		MtptoolpmOA oaryA = new MtptoolpmOA();
		oaryA.setTech_confirm_flg(techConfirmFlg);
		oaryA.setProd_confirm_flg(prodCinfirmFlg);
		oaryAlist.add(oaryA);
		outTrx.setOaryA(oaryAlist);
		return lRc;
	}

	/**
	 * 检查当前日期,同一机台，非请一个保养周期（pm_seq_id）是否设定相同保养类型
	 * @param //d1
	 * @return
	 */
	public boolean isSameSetting(String s_d, String s_t, String s_p, String s_s){
		boolean is_same = false;
		String hql_tool_pm = "FROM Ret_tool_pm where 1=1 and tool_id_fk='" + s_t
				+ "' and pm_type='" + s_p
//				+ "' and from_date=to_date('" + s_d + " 00:00:00','YYYY-MM-DD HH24:mi:ss')";
				+ "' and from_date='" + s_d + "'";
		if(!Util.isSpaceCheck(s_s)){
			hql_tool_pm += " and pm_seq_id<>'" + s_s + "'";
		}

		List<Ret_tool_pm> tool_pm_list = retToolPmDao.find(hql_tool_pm);
		if(!tool_pm_list.isEmpty()){
			is_same = true;
		}
		return is_same;
	}
	//更新TOOL状态
	private FtptolopeO updatetool_stat(String tool_id) throws Exception {
		FtptolopeI ftptolopeI = new FtptolopeI();
		FtptolopeIA iary = new FtptolopeIA();
		String too_id=tool_id;
		iary.setTool_id(tool_id);
		iary.setTool_stat("run");
		List<FtptolopeIA> iaryList1 = new ArrayList<>();
		iaryList1.add(iary);
		ftptolopeI.setIary(iaryList1);
		ftptolopeI.setAction_flg("A");
		FtptolopeO ftptolopeO = new FtptolopeO();
		ftptolopeO.setTrx_id("FTPTOLOPE");
		ftptolopeO.setTrx_id("O");
		String strOutTrx = ftptolopeService.subMainProc(AppContext.getCurrEventNumber(),
				JacksonUtil.toJSONStr(ftptolopeI));
		ftptolopeO = JacksonUtil.fromJson(strOutTrx, FtptolopeO.class);
		return ftptolopeO;
	}

	//判断保养是否过期
	public static boolean isDealy(String dataString){
		boolean is_delay = false;
		Date data = String2Date(dataString);
		Calendar calendar = Calendar.getInstance(); //得到日历
		Date d2 = calendar.getTime();
		if(d2.getTime() > data.getTime()){
			is_delay = true;
		}
		return is_delay;
	}

}
